<template>
    <avue-crud ref="gameCompanyRefs" :table-loading="tableLoading" v-model="form" :option="option"
        @refresh-change="getList" @row-save="rowSave" @row-update="rowUpdate" @row-del="rowDel" :data="data"
        :page="page" @size-change="sizeChange" @current-change="currentChange" @search-change="searchChange"
        @search-reset="searchReset" :cell-style="cellStyle" @selection-change="handleSelectionChange">
        <template #menu-left="{ size }">
            <el-button type="primary" @click="openCreateCodeDialog" :size="size">兑换码生成</el-button>
            <el-button type="success" @click="exportDoc" :size="size">导出文档</el-button>
            <el-button type="danger" @click="deleteCode" :size="size">批量删除</el-button>
        </template>
        <template #menu="{ row, index, size }">
            <el-button type="danger" text @click="lost(row)">失效</el-button>
            <el-button type="primary" text @click="look(row)">查看使用者</el-button>
        </template>
    </avue-crud>

    <el-dialog v-model="createCodeDialogVisible" title="生成兑换码">
        <el-form :model="createCodeForm">
            <el-form-item label="生成数量">
                <el-input v-model="createCodeForm.count" type="number"></el-input>
            </el-form-item>
            <el-form-item label="使用次数">
                <el-input v-model="createCodeForm.useCount" type="number"></el-input>
            </el-form-item>
            <el-form-item label="金币额度">
                <el-input v-model="createCodeForm.point" type="number"></el-input>
            </el-form-item>
            <el-form-item label="失效时间">
                <el-date-picker v-model="createCodeForm.invalidDay" type="datetime"
                    placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="createCodeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="createCode">生成</el-button>
        </div>
    </el-dialog>
    <DetailDialog :visible="detailVisible" v-model="detailVisible" :detailData="detail_data"
        @update:visible="detailVisible = $event" />


    <el-dialog style="width: 100%;" v-model="userListDialogVisible" title="使用者列表">
        <el-table :data="userList">
            <el-table-column prop="id" label="用户ID"></el-table-column>
            <el-table-column prop="time" label="使用时间"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" text @click="viewUser(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="userListDialogVisible = false">关闭</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import DetailDialog from '@/components/DetailDialog.vue'; // 引入DetailDialog组件
import { ref, reactive, onMounted } from "vue";
import gameCode from "@/options/gameCode";
import gameCompany from "@/options/gameCompany";
import { ElMessageBox, ElMessage } from "element-plus";
import {
    addCompany,
    getUserInfo,
    editCompany,
    delCompany,
    setcreateCode,
    setInvalid,
    getCodeList,
    delExchangeCode
} from "@/apis/admin";
import * as XLSX from 'xlsx';
const detailVisible = ref(false);
const option = gameCode;
const data = ref([]);
const page = reactive({
    total: 0,
    searchInfo: {},
    currentPage: 1,
    pageSize: 10,
});
const form = ref({});
const tableLoading = ref(false);
const selectedRows = ref([]); // Store selected rows
const detail_data = ref({});
const createCodeDialogVisible = ref(false);
const createCodeForm = reactive({
    useCount: 1,
    point: 0,
    count: 1,
    invalidDay: null
});
const generatedCodes = ref([]);

const userListDialogVisible = ref(false);
const userList = ref([]);

const sizeChange = (val) => {
    page.pageSize = val;
    getList();
};
const viewUser = (row) => {
    console.log('查看使用者', row.id);
    getUserInfo.post("", {
        userId: row.id
    }).then((res) => {
        detail_data.value = res.data;
        detailVisible.value = true;
    })
}
const currentChange = (val) => {
    page.currentPage = val;
    getList();
};
const searchChange = (form, done) => {
    page.searchInfo = form;
    page.currentPage = 1;
    getList();
    done();
};
const searchReset = () => {
    page.searchInfo = {};
    page.currentPage = 1;
    getList();
};
const deleteCode = () => {
    // 打印选中的行id
    console.log('多选删除列', selectedRows.value.map(item => item.code));
    delExchangeCode.post("", { codeList: selectedRows.value.map(item => item.code) }).then((res) => {
        if (res.code == 200) {
            ElMessage.success("删除成功!");
            getList();
        } else {
            ElMessage.error("删除失败!");
        }
    })
}
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex == 7) {
        let res = {
            color: "green",
            fontWeight: "bold",
            fontSize: "20",
        }
        switch (row.status) {
            case 0:
                res.color = 'green'
                break;
            case 1:
                res.color = '#9E9E9E'
                break;
            default:
                res.color = 'red'
                break;
        }
        return res
    }
};

const lost = (row) => {
    console.log('失效', row.code);
    setInvalid.post("", { code: row.code }).then((res) => {
        if (res.code == 200) {
            ElMessage.success("失效成功!");
            getList();
        } else {
            ElMessage.error("失效失败!");
        }
    })
}
const look = (row) => {
    console.log('查看使用者', row.id);
    // Mock user data
    userList.value = [
        { id: 176407309, time: '2023-01-01' },
        { id: 176407309, time: '2023-01-02' },
        { id: 176407309, time: '2023-01-03' },
        { id: 176407309, time: '2023-01-04' },
        { id: 176407309, time: '2023-01-05' },
        { id: 176407309, time: '2023-01-06' }
    ];
    userListDialogVisible.value = true;
}
const rowSave = async (row, done, loading) => {
    const res = await addCompany.post("", row);
    if (res.code == 200) {
        done();
        ElMessage.success("添加成功!");
        getList();
    } else {
        ElMessage.error("添加失败!");
    }
};
const rowDel = (row, index, done) => {
    ElMessageBox.confirm("此操作将永久删除该游戏公司, 是否继续?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        delCompany.post("", { id: row.id }).then((res) => {
            if (res.code == 200) {
                ElMessage.success("删除成功！");
                getList();
            } else {
                ElMessage.error("删除失败!");
            }
        });
    });
};
const rowUpdate = async (row, index, done, loading) => {
    const res = await editCompany.post("", row);
    if (res.code == 200) {
        done();
        ElMessage.success("编辑成功!");
        getList();
    } else {
        ElMessage.error("编辑失败!");
    }
};

const generateRandomCode = () => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 8; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
};
const openCreateCodeDialog = () => {
    console.log('兑换码生成')
    createCodeDialogVisible.value = true;
};
const createCode = () => {
    createCodeForm.count = parseInt(createCodeForm.count);
    createCodeForm.useCount = parseInt(createCodeForm.useCount);
    createCodeForm.point = parseInt(createCodeForm.point);
    createCodeForm.invalidDay = new Date(createCodeForm.invalidDay).getTime() / 1000;
    createCodeDialogVisible.value = false;

    // Generate codes and show them in a new dialog
    generatedCodes.value = [];
    for (let i = 0; i < createCodeForm.quantity; i++) {
        generatedCodes.value.push({ code: generateRandomCode() });
    }
    setcreateCode.post("", createCodeForm).then((res) => {
        createCodeForm.invalidDay = Date.now();
        if (res.code == 200) {
            getList();
            ElMessage.success("生成成功!");
        } else {
            ElMessage.error("生成失败!");
        }
    })
}
const getList = () => {
    tableLoading.value = true;
    data.value = [];

    getCodeList.post("", {
        searchInfo: page.searchInfo,
        page: page.currentPage,
        pageSize: page.pageSize,
    }).then((res) => {
        page.total = res.data.total;
        console.log('ssssss', res.data.list);
        // data.value = res.data.list;
        res.data.list.forEach(element => {
            let status = Math.floor(Math.random() * 2);
            let item = element;
            data.value.push({
                code: item.code, // Generate random 8-character code
                createAt: item.createAt,
                invalidAt: item.invalidAt,
                UseAt:item.UseAt,
                // 0 未使用 1 已使用 2 已失效
                useTime: item.status === 0 ? 0 : item.UseAt,
                status: item.status,
                cont: [item.useNum, item.useLimit],
                useId: status ? 176407309 : '-',
                point: item.point
            })
        });
        tableLoading.value = false;
    });
};
// 导出为文档
const exportDoc = () => {
    const exportData = data.value.map(item => {
        const { useId, UseAt,useNum,useLimit, invalidAt, $index, $cellEdit, status, createAt,cont,useTime, ...rest } = item;
        return {
            ...rest,
            失效时间: new Date(invalidAt * 1000).toLocaleString(),
            创建时间: new Date(createAt * 1000).toLocaleString(),
            使用次数:`${cont[0]}/${cont[1]}`,
        };
    });
    const ws = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, "兑换码列表.xlsx", { bookType: 'xlsx', type: 'blob' });
}
const submitForm = (formName) => {
    console.log(form.value);
    ElMessage.success("提交成功!");

};

const resetForm = (formName) => {
    const formRef = ref(formName);
    formRef.value.resetFields();
};

const addItem = (array, type = 'input') => {
    if (type === 'input') {
        array.push(0);
    } else if (type === 'stock') {
        array.push({
            JackPotWinRate: 0,
            JackPotHitVal: 0,
            JackPotShowVal: 0,
            JackPotHitRate: 0,
            CurrentJackPot: 0,
            CurrentStock: 0,
            Stock: [],
            Weight: [],
            StockDown: []
        });
    } else {
        array.push(JSON.parse(JSON.stringify(type)));
    }
};

const removeItem = (array, index) => {
    array.splice(index, 1);
};

const handleSelectionChange = (selection) => {
    selectedRows.value = selection;
    console.log('Selected rows:', selectedRows.value);
};

onMounted(() => {
    getList();
});
</script>